<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>尺码表生产工具</title>
    <base th:href="@{/}">
    <meta charset="utf-8" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
          name="viewport"/>
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap/tool-nav/sizeGenerator.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/bootstrap/css/my-layer-div.css}"/>
    <style>
        #removeCol,
        #removeRow {
            display: none;
            font-size: 1rem;
            width: 2rem;
            padding: .3rem .8rem;
            background: #367dff;
            color: #FFF;
            position: absolute;
            left: 100%;
            text-align: center;
            cursor: pointer;
        }

        #removeCol:hover,
        #removeRow:hover {
        }

    </style>
</head>
<body>
<div id="container">
    <div id="table">
        <div id="toolbar">
            <div class="toolbar_item">
                <span class="input"><input placeholder="请配置行数" title="行数配置" type="text" class="i_input"
                                           id="row"/></span>
                <span class="input"><input placeholder="请配置列数" title="列数配置" type="text" class="i_input"
                                           id="col"/></span>
                <span class="btn" id="generator">生成</span>
                <span class="btn" id="screenshot">截图</span>
            </div>
            <div class="toolbar_item">
                <span class="input"><input placeholder="请配置宽度(默认表宽1000px)" title="请配置宽度(默认表宽1000px)" type="text"
                                           class="i_input" id="wid"/></span>
                <span class="btn" id="resize">调整画布</span>
            </div>
            <div class="toolbar_item">
                <span class="input templ_content">
                    <span class="templ_checked" id="checked_size">请选择模板</span>
                    <ul class="templ_ul" id="templates">
                    </ul>
                </span>
                <span class="btn" id="useTempl">使用模板</span>
                <span class="btn" id="saveTempl">保存模板</span>
                <span class="btn" id="coverTempl">覆盖模板</span>
            </div>
        </div>
        <div id="table_show">
            <div id="header">
                <div class="tr">
                    <span class="th"><input type="text" placeholder="请使用上述操作定义你的专属表格" class="text_input"/></span>
                </div>
                <!--<div class="tr">
                    <span class="th">Size</span>
                    <span class="th">Shoulder Width(cm)</span>
                    <span class="th">Bust(cm)</span>
                    <span class="th">Length(cm)</span>
                    <span class="th">Waist(cm)</span>
                </div>-->
            </div>
            <div id="body">
                <div class="tr">
                    <span class="td"><input type="text" placeholder="此内容为展示用例" class="text_input"/></span>
                </div>
                <!--<div class="tr">
                    <span class="td">XL</span>
                    <span class="td">50cm</span>
                    <span class="td">121cm</span>
                    <span class="td">77cm</span>
                    <span class="td">112-119cm</span>
                </div>
                <div class="tr">
                    <span class="td">XXL</span>
                    <span class="td">53cm</span>
                    <span class="td">129cm</span>
                    <span class="td">81cm</span>
                    <span class="td">120-128cm</span>
                </div>
                <div class="tr">
                    <span class="td">3XL</span>
                    <span class="td">56cm</span>
                    <span class="td">137cm</span>
                    <span class="td">84cm</span>
                    <span class="td">129-137cm</span>
                </div>
                <div class="tr">
                    <span class="td">4XL</span>
                    <span class="td">59cm</span>
                    <span class="td">145cm</span>
                    <span class="td">86cm</span>
                    <span class="td">138-145cm</span>
                </div>
                <div class="tr">
                    <span class="td">5XL</span>
                    <span class="td">62cm</span>
                    <span class="td">153cm</span>
                    <span class="td">88cm</span>
                    <span class="td">146-153cm</span>
                </div>
                <div class="tr">
                    <span class="td">6XL</span>
                    <span class="td">64cm</span>
                    <span class="td">160cm</span>
                    <span class="td">90cm</span>
                    <span class="td">154-160cm</span>
                </div>-->
            </div>
        </div>
        <div id="removeRow">
            删除
        </div>
        <div id="removeCol">
            删除
        </div>
    </div>
</div>
<div id="footer">
    <span class="back_btn" data-link="/">回到首页</span>
    <span class="back_btn" data-link="tool/toolNav">更多工具</span>
</div>
<script type="text/javascript" th:src="@{https://lib.baomitu.com/jquery/3.5.0/jquery.min.js}"></script>
<script type="text/javascript" th:src="@{https://cdn.bootcdn.net/ajax/libs/layer/3.1.1/layer.min.js}"></script>
<!--<script type="text/javascript"
        th:src="@{https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js}"></script>-->
<script type="text/javascript" th:src="@{/bootstrap/tool-nav/html2canvas.min.js}"></script>
<script type="text/javascript" th:src="@{/bootstrap/js/layopen.js}"></script>
<script type="text/javascript" th:src="@{/bootstrap/js/JSONUtil.js}"></script>
<script type="text/javascript" th:src="@{/bootstrap/js/AjaxUtil.js}"></script>
<script type="text/javascript">
    let ALL_SIZE = {};
    let DATA = {
        'Size': ['S', 'M', 'L', 'XL', 'XXL'],
        'Shoulder Width(cm)': ['20', '30', '40', '50', '60'],
        'Bust(cm)': ['20', '30', '40', '80', '60'],
        'Length(cm)': ['20', '30', '40', '70', '60'],
        'Waist(cm)': ['20', '30', '40', '60', '60']
    };

    window.onload = function () {
        loadAllSize();
    };


    /*$("#body").on('mouseenter', '.tr .td', function () {
        let top = $(this).offset().top;
        let left = $(this).offset().left;
        $('#removeRow').css('top', top + 'px').stop().fadeIn();
        // $('#removeCol').css('left', left + 'px').stop().fadeIn();
    });

    $("#body").on('mouseleave', function (e) {
        var div = document.getElementById("removeRow");
        var x = e.clientX;
        var y = e.clientY;
        var divx1 = div.offsetLeft;
        var divy1 = div.offsetTop;
        var divx2 = div.offsetLeft + div.offsetWidth;
        var divy2 = div.offsetTop + div.offsetHeight;
        if (x < divx1 || x > divx2 || y < divy1 || y > divy2) {
            console.log(111);
        } else {
            $("#removeRow").stop().fadeOut();
        }
    });*/

    /*$("#removeRow").on('mouseleave', function () {
        $(this).stop().fadeOut();
    });*/


    /**
     * 生成
     */
    $('#generator').on('click', function () {
        // 行列
        let row = $('#row').val();
        if (!row) {
            WarnAlert('请输入合法行数继续');
            return;
        }
        let col = $('#col').val();
        if (!col) {
            WarnAlert('请输入合法列数继续');
            return;
        }
        generatorTable(row, col);
        reSize();
    });

    /**
     *  调整画布: 初始值1000px
     */
    $('#resize').on('click', function () {
        let wid = $('#wid').val();
        if (wid) {
            if (parseInt(wid) < 800) {
                WarnAlert('不在合法宽度内(>= 800)');
                return;
            }
            let bdW = document.body.clientWidth;
            if (parseInt(wid) > bdW) {
                WarnAlert('宽度设置不能超过屏幕可见宽度(' + bdW + ')');
                return;
            }
            $('#table').css('width', '' + wid + 'px');
            reSize();
        } else {
            WarnAlert('请输入你需要调整的尺寸大小');
        }
    });

    /**
     * 使用模板
     */
    $('#useTempl').on('click', function () {
        let sizeKey = $('#checked_size').attr('data-id');
        if (!sizeKey || sizeKey === '') {
            WarnAlert('当前未选择任何模板, 请选择后再操作');
            return;
        }
        let size = JSON.parse(ALL_SIZE[sizeKey].content);
        let headHtml = '', bodyHtml = '', keys = [], vCount = 0;
        for (let key in size) {
            headHtml += '<span class="th"><input type="text" value="' + key + '" class="text_input"/></span>';
            keys.push(key);
            vCount += size[key].length;
        }
        for (let i = 0; i < vCount / (keys.length); i++) {
            let tr = '<div class="tr">';
            for (let j = 0; j < keys.length; j++) {
                let v = keys[j];
                let value = size[v];
                tr += '<span class="td"><input type="text" value="' + value[i] + '" class="text_input"/></span>';
            }
            bodyHtml += tr + '</div>';
        }
        $('#header .tr').eq(0).empty().html(headHtml);
        $('#body').empty().html(bodyHtml);
        reSize();
    });

    /**
     * 保存模板
     */
    $('#saveTempl').on('click', function () {
        layer.confirm('您是否添加当前使用模板？', {
            btn: ['添加', '取消'] //按钮
        }, function () {
            layer.closeAll();
            layer.prompt({title: '输入模板名称，并确认', formType: 0}, function (title, index) {
                layer.close(index);
                let table = getTableData(), sizeData = {};
                if (table == null) {
                    WarnAlert('当前表格表头部分必填部分未填写');
                    return;
                }
                sizeData['title'] = title;
                sizeData['content'] = JSON.stringify(table);
                let size = clearIgnoreFile(sizeData);
                ajaxPost("tool/ali/size/addOrUpdateSizeTable", size, function () {
                }, function (result) {
                    result = JSONUtil.parseObj(result);
                    if (result.code + '' === '200') {
                        let data = result.data;
                        let key = data.sizeKey;
                        let li = '<li data-id="' + key + '" class="templ_li">' + data.title + '</li>';
                        $('#templates').append(li);
                        SuccessAlert('保存成功');
                    } else {
                        WarnAlert(result.message);
                    }
                }, function (e) {
                    ErrorAlert('请求出错, 请稍后重试');
                });
            });
        }, function () {

        });
    });

    /**
     * 覆盖模板
     */
    $('#coverTempl').on('click', function () {
        layer.confirm('您是否需要更新当前模板？', {
            btn: ['更新', '取消'] //按钮
        }, function () {
            let sizeKey = $('#checked_size').attr('data-id');
            if (!sizeKey || sizeKey === '') {
                WarnAlert('当前未选择任务可覆盖模板哦');
                return;
            }
            let data = ALL_SIZE[sizeKey];
            let table = getTableData();
            if (table == null) {
                WarnAlert('当前表格表头部分必填部分未填写');
                return;
            }
            data['content'] = JSON.stringify(table);
            let size = clearIgnoreFile(data);
            ajaxPost("tool/ali/size/addOrUpdateSizeTable", size, function () {
            }, function (result) {
                result = JSONUtil.parseObj(result);
                if (result.code + '' === '200') {
                    let data = result.data;
                    let key = data.sizeKey;
                    ALL_SIZE[key] = data;
                    SuccessAlert('更新完成');
                } else {
                    WarnAlert(result.message);
                }
            }, function (e) {
                ErrorAlert('请求出错, 请稍后重试');
            });
        }, function () {
        });
    });

    /**
     * 切换模板
     */
    $('#templates').on('click', '.templ_li', function () {
        let sizeKey = $(this).attr('data-id');
        $('#checked_size').attr('data-id', sizeKey).text($(this).text());
    });

    /**
     * 页面截图
     */
    $('#screenshot').on('click', function () {
        let $checked = $('#checked_size');
        let $table = $('#table_show'), checkSize = 'size_' + $checked.text() + $checked.data('id');
        if (!$checked.data('id')) {
            checkSize = 'size_' + new Date().getTime();
        }
        html2canvas($table, {
            allowTaint: true,
            taintTest: false,
            useCORS: true,//火狐浏览器添加项
            scale: 2,
            dpi: 192,
            // scale: window.devicePixelRatio,
            onrendered: function (canvas) {
                var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                var userAgent = navigator.userAgent;
                //判断是否是IE11
                if (-1 !== userAgent.indexOf("Trident")) {
                    var arr = image.split(',');
                    var mime = arr[0].match(/:(.*?);/)[1];
                    var bstr = atob(arr[1]);
                    var n = bstr.length;
                    var u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    window.navigator.msSaveBlob(new Blob([u8arr], {type: mime}), checkSize + ".jpg");
                } else {
                    canvas.id = "mycanvas";
                    //生成base64图片数据
                    var dataUrl = canvas.toDataURL();
                    var newImg = document.createElement("img");
                    newImg.src = dataUrl;
                    var a = $("<a></a>").attr("href", dataUrl).attr("download", checkSize + ".jpg");
                    $("body").append(a);//火狐浏览器添加项
                    a[0].click();
                    a.remove();
                }
            }
        });
    });


    /**
     * 宽度适应
     */
    function reSize() {
        let $th = $('#header .tr .th'), $td = $('#body .tr .td');
        let thLen = $th.length;
        let totalW = $('#header').width();
        $th.css({'width': '' + totalW / thLen + 'px'});
        $td.css({'width': '' + totalW / thLen + 'px'});
        $('#footer').css('width', totalW + 'px');
    }

    /**
     * 生成表的HTML代码
     * @param row 行
     * @param col 列
     */
    function generatorTable(row, col) {
        let headHtml = '', bodyHtml = '';
        for (let j = 0; j < col; j++) {
            headHtml += '<span class="th"><input type="text" class="text_input"/></span>';
        }
        for (let i = 0; i < row; i++) {
            let bodyTr = '<div class="tr">';
            for (let i = 0; i < col; i++) {
                bodyTr += '<span class="td"><input type="text" class="text_input"/></span>';
            }
            bodyHtml += bodyTr + '</div>';
        }
        $('#header .tr').eq(0).empty().html(headHtml);
        $('#body').empty().html(bodyHtml);
    }

    /**
     * 获取表格数据
     */
    function getTableData() {
        let data = {}, $th = $('#header .tr').eq(0).find('.th'), $bdTr = $('#body .tr');
        if ($th.length > 0) {
            let keys = [];
            for (let i = 0; i < $th.length; i++) {
                let $v = $th.eq(i);
                let key = $v.find('.text_input').eq(0).val();
                if (!key || key === '') {
                    return null;
                }
                data[key] = [];
                keys.push(key);
            }
            for (let i = 0; i < $bdTr.length; i++) {
                let $input = $bdTr.eq(i).find('.text_input');
                if ($input.length > 0) {
                    for (let i = 0; i < $input.length; i++) {
                        let key = keys[i];
                        let v = $input.eq(i).val();
                        data[key].push(v);
                    }
                }
            }
        }
        return data;
    }

    /**
     * 假装所有模板
     */
    function loadAllSize() {
        ajaxPost("tool/ali/size/getSizeTables", {}, function () {
        }, function (result) {
            result = JSONUtil.parseObj(result);
            if (result.code + '' === '200') {
                let sizes = result.data;
                for (let i = 0; i < sizes.length; i++) {
                    let v = sizes[i];
                    let key = v.sizeKey;
                    ALL_SIZE[key] = v;
                }
                settingTemplate();
            } else {
                WarnAlert(result.message);
            }
        }, function (e) {
            ErrorAlert('请求出错, 请稍后重试');
        });
    }

    /**
     * 设置模板
     */
    function settingTemplate() {
        let templ = '';
        for (let key in ALL_SIZE) {
            let v = ALL_SIZE[key];
            templ += '<li data-id="' + key + '" class="templ_li">' + v.title + '</li>';
        }
        $('#templates').empty().html(templ);
    }

    /**
     * 清除非必要字段
     */
    function clearIgnoreFile(data) {
        let newData = {};
        newData['sizeKey'] = data['sizeKey'];
        newData['title'] = data['title'];
        newData['content'] = data['content'];
        return newData;
    }

    $('.back_btn').on('click', function () {
        let link = $(this).data('link');
        window.location.href = link;
    });
</script>
</body>
</html>
